package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.GoogleRefreshLayout.OnScrollListener;
import com.core.lib.widget.MyDialog;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import com.lepu.app.fun.bbs.adapter.AdapterBbs;
import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.usercenter.bean.BeanUserOther;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

/**
 * 个人主页
 * 
 * @author wxd
 * 
 */
public class MyUserOtherInfoActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnRefreshListener,
		OnLoadListener, OnScrollListener {

	private static final String REQUEST_INFO = "request_info";
	private static final String REQUEST_FOLLOW = "request_follow";
	private static final String REQUEST_FOLLOW_CANCEL = "request_follow_cancel";

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 20;
	private static final int MSG_DATA_FAIL = 21;
	private static final int MSG_DATA_MORE_SUCCESS = 22;
	private static final int MSG_DATA_MORE_FAIL = 23;

	private static final int MSG_INFO_SUCCESS = 10;
	private static final int MSG_INFO_FAIL = 11;

	private static final int MSG_FOLLOW_SUCCESS = 12;
	private static final int MSG_FOLLOW_FAIL = 13;
	private static final int MSG_FOLLOW_CANCEL_SUCCESS = 14;
	private static final int MSG_FOLLOW_CANCEL_FAIL = 15;

	private String mUserID = "";
	private BeanUserOther mBeanUserOther = null;

	private CircularImageView mHeadImageView;
	private TextView mHeadTextView;// username
	private ImageView mFollowImageView;// 关注操作
	private TextView mFansTextView;// 粉丝数量
	private TextView mFollowTextView;// 关注数量
	private TextView mCustomFeelTextView;// 个性签名

	private LinearLayout mTopLayout;
	
	private CustomTopBarNew mTopbar;

	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterBbs mDataAdapter = null;
	private ArrayList<BeanBbs> mDataArrayList = null;
	private int mCurrentPage = 1;
	private String mMaxThreadID = "-1";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_user_other_info_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("");
		mTopbar.setonTopbarNewLeftLayoutListener(this);

		mUserID = getIntent().getStringExtra("targetId");

		mTopLayout = (LinearLayout) findViewById(R.id.topLayout);
		mHeadImageView = (CircularImageView) findViewById(R.id.accountIconImageView);
		mHeadTextView = (TextView) findViewById(R.id.usernameTextView);
		mFollowImageView = (ImageView) findViewById(R.id.followImageView);
		mFansTextView = (TextView) findViewById(R.id.fansTextView);
		mFollowTextView = (TextView) findViewById(R.id.followTextView);
		mCustomFeelTextView = (TextView) findViewById(R.id.customFeelTextView);
		
		mHeadImageView.setImageResource(R.drawable.app_ic_default_avatar);

		LinearLayout fansLayout = (LinearLayout) findViewById(R.id.fansLayout);
		LinearLayout followLayout = (LinearLayout) findViewById(R.id.followLayout);

		fansLayout.setOnClickListener(mOnClickListener);
		followLayout.setOnClickListener(mOnClickListener);
		mFollowImageView.setOnClickListener(mOnClickListener);

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setOnScrollListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		requestInfo();

		requestList(false);
	}

	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					noDataLayout.setVisibility(View.VISIBLE);
				}
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}

				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.fansLayout: // 粉丝
				Intent intentFensi = new Intent(MyUserOtherInfoActivity.this,
						MyFenSiActivity.class);
				intentFensi.putExtra("fensi_guanzhu",
						MyFenSiActivity.TYPE_FENSI);
				intentFensi.putExtra("TargetUserID", mUserID);
				startActivity(intentFensi, true);

				break;
			case R.id.followLayout: // 关注

				Intent intentGuanzhu = new Intent(MyUserOtherInfoActivity.this,
						MyFenSiActivity.class);
				intentGuanzhu.putExtra("fensi_guanzhu",
						MyFenSiActivity.TYPE_GUANZHU);
				intentGuanzhu.putExtra("TargetUserID", mUserID);
				startActivity(intentGuanzhu, true);
				break;

			case R.id.followImageView:
				if (mBeanUserOther == null) {
					return;
				}

				if (mBeanUserOther.Relation.equals("3")) { // 未关注
					requestFollow(mBeanUserOther.UserID);
					UmengHelper.CustomEvent(MyUserOtherInfoActivity.this, UmengEvent.event_luntan_attention);
				} else { // 已关注
					new MyDialog(MyUserOtherInfoActivity.this)
							.setMessage("您确定取消关注吗?")
							.setNegativeButton(R.string.app_cancel,
									new View.OnClickListener() {

										@Override
										public void onClick(View v) {

										}
									})
							.setPositiveButton(R.string.app_ok,
									new View.OnClickListener() {

										@Override
										public void onClick(View v) {
											requestFollowCancel(mBeanUserOther.UserID);
										}
									}).create(null).show();

				}
				break;
			default:
				break;
			}
		}
	};

	// 获取数据
	public void requestInfo() {
		String url = Setting.getUserFollowFansUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			
			params.put("TargetUserID", mUserID);
		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post(url, map, null, this, REQUEST_INFO, true);
	}

	// 关注
	public void requestFollow(String targetId) {
		String url = Setting.getUserFollowUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("TargetUserID", targetId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_FOLLOW, true);
	}

	// 取消关注
	public void requestFollowCancel(String targetId) {
		String url = Setting.getUserFollowCancelUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("TargetUserID", targetId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_FOLLOW_CANCEL, true);
	}

	// 请求数据
	public void requestList(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
			mMaxThreadID = "-1";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("TargetUserID", mUserID);
			params.put("MaxThreadID", mMaxThreadID);

			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);

		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(Setting.getThreadListByUserUrl(), map, null, this,
				request, true, false, true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_INFO_SUCCESS:
				
				hideProgressDialog();

				if (mBeanUserOther.Relation.equals("1")) {
					mFollowImageView
							.setBackgroundResource(R.drawable.my_follow_has_selector);
				} else if (mBeanUserOther.Relation.equals("2")) {
					mFollowImageView
							.setBackgroundResource(R.drawable.my_follow_each_selector);
				} else if (mBeanUserOther.Relation.equals("3")) {
					mFollowImageView
							.setBackgroundResource(R.drawable.my_follow_selector);
				}

				UniversalImageLoadTool.disPlay(
						Setting.getHeadIconUrl(mBeanUserOther.UserID),
						mHeadImageView, R.drawable.app_ic_default_avatar);
				mHeadTextView.setText(mBeanUserOther.NickName);
				mFansTextView.setText(mBeanUserOther.FansCount);
				mFollowTextView.setText(mBeanUserOther.FollowCount);

				if (!TextUtils.isEmpty(mBeanUserOther.Whatsup)) {
					mCustomFeelTextView.setText(mBeanUserOther.Whatsup);
				}
				
				mTopbar.setTopbarTitle(mBeanUserOther.NickName);

				break;
			case MSG_INFO_FAIL:
				hideProgressDialog();
				break;
			case MSG_FOLLOW_SUCCESS:
				int follow1 = BeanUserOther.parseJsonFollow((String) msg.obj);

				if (follow1 == 1) { // 自己关注
					mFollowImageView
							.setBackgroundResource(R.drawable.my_follow_has_selector);
					mBeanUserOther.Relation = "1";
				} else if (follow1 == 2) { // 互相关注
					mFollowImageView
							.setBackgroundResource(R.drawable.my_follow_each_selector);
					mBeanUserOther.Relation = "2";
				}

				mBeanUserOther.FansCount = String.valueOf(Integer
						.valueOf(mBeanUserOther.FansCount) + 1);
				mFansTextView.setText(mBeanUserOther.FansCount);
				break;
			case MSG_FOLLOW_FAIL:

				break;

			case MSG_FOLLOW_CANCEL_SUCCESS:

				mFollowImageView
						.setBackgroundResource(R.drawable.my_follow_selector);
				mBeanUserOther.Relation = "3";

				mBeanUserOther.FansCount = String.valueOf(Integer
						.valueOf(mBeanUserOther.FansCount) - 1);
				mFansTextView.setText(mBeanUserOther.FansCount);
				break;
			case MSG_FOLLOW_CANCEL_FAIL:

				break;
			case MSG_DATA_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanBbs> dataList = (ArrayList<BeanBbs>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList = dataList;
					
					mMaxThreadID = mDataArrayList.get(0).bbsID;
					
				} else {
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
					
					UIHelper.showToast(MyUserOtherInfoActivity.this,
							R.string.no_data);
					showHideNoDataLayout(true);
				}

				ImageView tempImageView = new ImageView(MyUserOtherInfoActivity.this);
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new AdapterBbs(MyUserOtherInfoActivity.this,
						mDataArrayList, 4,false);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				// 第一次请求用这个
				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);

				break;
			case MSG_DATA_MORE_SUCCESS:

				@SuppressWarnings("unchecked")
				ArrayList<BeanBbs> dataMoreList = (ArrayList<BeanBbs>) msg.obj;

				if (dataMoreList != null && dataMoreList.size() > 0) {

					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MyUserOtherInfoActivity.this,
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		requestList(true);
	}

	@Override
	public void onRefresh() {
		requestList(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_INFO)) {
			mBeanUserOther = BeanUserOther
					.parseJsonData((String) data);

			if(mBeanUserOther != null && !TextUtils.isEmpty(mBeanUserOther.Relation))
			{
				mHandler.sendEmptyMessage(MSG_INFO_SUCCESS);
			}else{
				mHandler.sendEmptyMessage(MSG_INFO_FAIL);
			}
		} else if (object.equals(REQUEST_FOLLOW)) {

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FOLLOW_SUCCESS;
			msg.obj = data;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_FOLLOW_CANCEL)) {

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FOLLOW_CANCEL_SUCCESS;
			msg.obj = null;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA)) {
			ArrayList<BeanBbs> dataArraylist = BeanBbs
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			ArrayList<BeanBbs> dataMoreArraylist = BeanBbs
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mDataArrayList.addAll(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_INFO)) {
			mHandler.sendEmptyMessage(MSG_INFO_FAIL);
		} else if (object.equals(REQUEST_FOLLOW)) {
			mHandler.sendEmptyMessage(MSG_FOLLOW_FAIL);
		} else if (object.equals(REQUEST_FOLLOW_CANCEL)) {
			mHandler.sendEmptyMessage(MSG_FOLLOW_CANCEL_FAIL);
		} else if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}
	}

	/**
	 * 滑动隐藏topbar
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		if (firstVisibleItem > 1) {
			mTopLayout.setVisibility(View.GONE);
		} else if (firstVisibleItem < 1) {
			mTopLayout.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == 0) {
			UniversalImageLoadTool.resume();
		} else {
			UniversalImageLoadTool.pause();
		}
	}

}
